⚡️ Speed up function print_version by 201%
#7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 201% (2.01x) speedup for
print_versioninsrc/together/cli/cli.py⏱️ Runtime :
23.2 microseconds→7.71 microseconds(best of35runs)📝 Explanation and details
The optimization replaces
click.echo()withsys.stdout.write()for outputting the version string. The key performance improvement comes from avoiding the overhead ofclick.echo(), which includes additional formatting, color handling, and abstraction layers that aren't needed for simple text output.Specific changes:
import systo use the standard library's direct stdout writingclick.echo(f"Version {together.version}")withsys.stdout.write(f"Version {together.version}\n")\nto maintain identical output behaviorWhy this is faster:
click.echo()performs several internal operations including checking for color support, handling different output streams, and text processing.sys.stdout.write()bypasses all this overhead and writes directly to stdout, which is significantly faster for simple string output.The line profiler shows the output line dropped from 1.38ms (73.6% of total time) to 0.17ms (26.2% of total time) - a ~8x improvement on that specific line, contributing to the overall 200% speedup.
Test case performance:
The optimization particularly benefits test cases that trigger the print functionality, such as
test_print_version_ctx_exit_called_once(265% faster) andtest_print_version_ctx_exit_raises(405% faster), where the reduced overhead of direct stdout writing compounds across multiple executions.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-print_version-mgzs0v9uand push.